﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Hxsoft.AppV1.Module;
using Hxsoft.AppV1.WebUI;

namespace Hxsoft.AppV1._Controls
{
	public partial class ResourceSelector : Hxsoft.AppV1.UserControl
	{
		protected string SearchText
		{
			get { return Res.SearchText; }
		}

		protected string ZoomInText
		{
			get { return Res.ZoomInText; }
		}

		protected string DeleteText
		{
			get { return Res.DeleteText; }
		}

		protected string LoadDataButtonText
		{
			get { return Res.ResourceSelector_LoadDataButtonText; }
		}

		private LoadedValue<int?> loadedSiteId;
		public int? SiteId
		{
			get {
				if (loadedSiteId.Loader == null)
					loadedSiteId.Loader = () =>
						{
							var siteId = (int?)ViewState["SiteId"];
							if (!siteId.HasValue)
								siteId = IntExtensions.ParseOrNull(Request.QueryString["SiteId"]);
							if (!siteId.HasValue)
								siteId = Sites.CurrentSiteId;
							return siteId;
						};
				return loadedSiteId.Value;
			}
			set {
				if (loadedSiteId.Setter == null)
					loadedSiteId.Setter = v => ViewState["SiteId"] = v;
				loadedSiteId.Value = value;
			}
		}

		private LoadedValue<Guid> loadedGlobalId;
		public Guid GlobalId
		{
			get
			{
				if (loadedGlobalId.Loader == null)
					loadedGlobalId.Loader = () => ObjectExtensions.ConvertFromOrDefault<Guid>(ViewState["GlobalId"]);
				return loadedGlobalId.Value;
			}
			set
			{
				if (loadedGlobalId.Setter == null)
					loadedGlobalId.Setter = v => ViewState["GlobalId"] = v;
				loadedGlobalId.Value = value;
			}
		}

		private LoadedValue<string> loadedInfoType;
		public string InfoType
		{
			get
			{
				if (loadedInfoType.Loader == null)
					loadedInfoType.Loader = () => (string)ViewState["InfoType"];
				return loadedInfoType.Value;
			}
			set
			{
				if (loadedInfoType.Setter == null)
					loadedInfoType.Setter = v => ViewState["InfoType"] = v;
				loadedInfoType.Value = value;
			}
		}

		private LoadedValue<string> loadedFilterResourceTypeName;
		public string FilterResourceTypeName
		{
			get
			{
				if (loadedFilterResourceTypeName.Loader == null)
					loadedFilterResourceTypeName.Loader = () => (string)ViewState["FilterResourceTypeName"];
				return loadedFilterResourceTypeName.Value;
			}
			set
			{
				if (loadedFilterResourceTypeName.Setter == null)
					loadedFilterResourceTypeName.Setter = v => ViewState["FilterResourceTypeName"] = v;
				loadedFilterResourceTypeName.Value = value;
			}
		}

		private LoadedValue<string> loadedClientCallbackFunction;
		public string ClientCallbackFunction
		{
			get
			{
				if (loadedClientCallbackFunction.Loader == null)
					loadedClientCallbackFunction.Loader = () => (string)ViewState["ClientCallbackFunction"];
				return loadedClientCallbackFunction.Value;
			}
			set
			{
				if (loadedClientCallbackFunction.Setter == null)
					loadedClientCallbackFunction.Setter = v => ViewState["ClientCallbackFunction"] = v;
				loadedClientCallbackFunction.Value = value;
			}
		}

		private LoadedValue<bool> loadedIsGetRealResourceUrl;
		public bool IsGetRealResourceUrl
		{
			get
			{
				if (loadedIsGetRealResourceUrl.Loader == null)
					loadedIsGetRealResourceUrl.Loader = () => BooleanExtensions.ConvertFromOrDefault(ViewState["IsGetRealResourceUrl"], false);
				return loadedIsGetRealResourceUrl.Value;
			}
			set
			{
				if (loadedIsGetRealResourceUrl.Setter == null)
					loadedIsGetRealResourceUrl.Setter = v => ViewState["IsGetRealResourceUrl"] = v;
				loadedIsGetRealResourceUrl.Value = value;
			}
		}

		private LoadedValue<bool> loadedIsCloseWindow;
		public bool IsCloseWindow
		{
			get
			{
				if (loadedIsCloseWindow.Loader == null)
					loadedIsCloseWindow.Loader = () => BooleanExtensions.ConvertFromOrDefault(ViewState["IsCloseWindow"], false);
				return loadedIsCloseWindow.Value;
			}
			set
			{
				if (loadedIsCloseWindow.Setter == null)
					loadedIsCloseWindow.Setter = v => ViewState["IsCloseWindow"] = v;
				loadedIsCloseWindow.Value = value;
			}
		}

		public bool IsStartLoadData
		{
			get
			{
				return CtrLoadDataContainer.Visible;
			}
			set
			{
				CtrLoadDataButton.Visible = !value;
				CtrLoadDataContainer.Visible = value;
			}
		}

		public int PageSize
		{
			get { return CtrPager.PageSize; }
			set { CtrPager.PageSize = value; }
		}

		protected string GetUploaderUrl()
		{
			return GenericUrlManager.GetInfoResourceUploaderUrl(GlobalId, InfoType, FilterResourceTypeName, string.IsNullOrEmpty(ClientCallbackFunction) ? null : this.ClientID + "_ResourceItemClick", SiteId);
		}

		protected string GetClickResourceItemScript()
		{
			string script = @"function " + this.ClientID + @"_ResourceItemClick(resourceInfo){";
			if (!string.IsNullOrEmpty(ClientCallbackFunction))
			{
				if (IsGetRealResourceUrl)
					script += @"this.getUrl = " + GenericUrlManager.GetInfoResourceThumbnailGeneratorUrl_ClientScript() + @";jQuery.pageCallback(""" + ClientCallbackFunction + @""", this.getUrl(resourceInfo.resourceId, null, resourceInfo.resourceType));";
				else
					script += @"jQuery.pageCallback(""" + ClientCallbackFunction + @""", resourceInfo);";

				if(IsCloseWindow) script += "top.close();";
			}
			else
				script += this.ClientID + @"_OpenResource(resourceInfo);";
			script += @"}";

			script += @"function " + this.ClientID + @"_OpenResource(resourceInfo){";
			script += @"this.getOpenResourceUrl = " + GenericUrlManager.GetInfoResourceThumbnailGeneratorUrl_ClientScript() + ";";
			script += @"window.open(this.getOpenResourceUrl(resourceInfo.resourceId, null, resourceInfo.resourceType));";
			script += @"}";

			return script;
		}

		protected void CtrPager_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
		{
			CtrPager.CurrentPageIndex = e.NewPageIndex;
			CtrList.DataBind();
		}

		protected override void OnPreRender(EventArgs e)
		{
			this.ApplicationPage.RegisterHeadIncludeFile(ApplicationConfiguration.JQueryUrl, IncludeFileType.JS);
			this.ApplicationPage.RegisterHeadIncludeFile(ApplicationConfiguration.CommonScriptUrl, IncludeFileType.JS);
			this.ApplicationPage.RegisterHeadIncludeFile(ApplicationConfiguration.ResourceSelectorStyleUrl, IncludeFileType.CSS);

			CtrSearchButton.Text = SearchText;
			CtrReloadButton.Text = Res.ReloadText;

			base.OnPreRender(e);
		}

		protected void CtrList_DataBinding(object sender, EventArgs e)
		{
			if (!IsStartLoadData) return;

			string[] filterResourceTypes = null;
			if (!string.IsNullOrEmpty(FilterResourceTypeName))
			{
				string filterResourceType = UploadRule.GetFilterResourceType(FilterResourceTypeName);
				if (!string.IsNullOrEmpty(filterResourceType)) filterResourceTypes = filterResourceType.Split(UploadRule.FileTypeSeparator);
			}
			PaginationInfo<List<InfoResources.InfoResourceBaseInfo>> pageInfo = InfoResources.GetPaginationBaseInfoItems(GlobalId, CtrKeyword.Text, filterResourceTypes, CtrPager.PageSize, CtrPager.CurrentPageIndex);
			CtrPager.RecordCount = pageInfo.RecordCount;
			CtrList.DataSource = pageInfo.Records;
		}

		protected void CtrList_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
			{
				Literal CtrResourceIcoBox = (Literal)e.Item.FindControl("CtrResourceIcoBox");
				Literal CtrResourceTextBox = (Literal)e.Item.FindControl("CtrResourceTextBox");
				InfoResources.InfoResourceBaseInfo resource = (InfoResources.InfoResourceBaseInfo)e.Item.DataItem;

				string linkTag = @"<a href=""javascript:" + this.ClientID + @"_ResourceItemClick({'resourceId' : '" + resource.ResourceId + @"', 'resourceType' : '" + resource.ResourceType + @"'});"">{0}</a>";

				string str = @"<img src=""" + GenericUrlManager.GetInfoResourceThumbnailGeneratorUrl(resource.ResourceId, GenericCommon.InfoResourceCopyName_ResourceSelector) + @""" alt=""" + resource.Name + @""">";
				str = linkTag.Replace("{0}", str);
				CtrResourceIcoBox.Text = str;

				str = linkTag.Replace("{0}", resource.Name);
				CtrResourceTextBox.Text = str;
			}
		}

		protected void CtrSearchButton_Click(object sender, EventArgs e)
		{
			CtrPager.CurrentPageIndex = 1;
			CtrList.DataBind();
		}

		protected void CtrList_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			int identifier = GetListItemIdentifier(e.Item);
			string messages = "";

			switch (e.CommandName)
			{
				case "Delete":
					messages = Delete(identifier);
					break;
			}

			if (!String.IsNullOrEmpty(messages))
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.PageMessage_OperateErrorTitle, messages));
			}

			CtrList.DataBind();
		}

		/// <summary>
		/// 删除指定的信息
		/// </summary>
		/// <param name="identifier">要删除信息的标识符。</param>
		/// <returns>如果删除发生错误则返回错误消息。</returns>
		protected string Delete(int identifier)
		{
			try
			{
				InfoResources.Delete(identifier);
			}
			catch (Exception e)
			{
				return e.Message;
			}
			return null;
		}

		/// <summary>
		/// 取得 ListItem 的标识符。
		/// </summary>
		/// <param name="moduleItem">列表的 ListItem。</param>
		/// <returns>ListItem 的标识符。</returns>
		protected int GetListItemIdentifier(RepeaterItem item)
		{
			int identifier;
			HiddenField control;

			control = (HiddenField)item.FindControl("CtrResourceId");
			identifier = Convert.ToInt32(control.Value);

			return identifier;
		}

		protected void CtrReloadButton_Click(object sender, EventArgs e)
		{
			CtrList.DataBind();
		}

		protected void CtrLoadDataButton_Click(object sender, EventArgs e)
		{
			IsStartLoadData = true;
			CtrList.DataBind();
		}
	}
}